import os
from PIL import Image

def crop_images_in_directory(directory, output_directory, left, top, right, bottom):
    """
    对目录下的所有JPG图像进行裁剪
    :param directory: 输入图像所在目录
    :param output_directory: 输出图像保存目录
    :param left: 裁剪区域左边界
    :param top: 裁剪区域上边界
    :param right: 裁剪区域右边界
    :param bottom: 裁剪区域下边界
    """
    # 确保输出目录存在
    os.makedirs(output_directory, exist_ok=True)
    
    # 遍历目录下的所有文件
    for filename in os.listdir(directory):
        if filename.lower().endswith('.jpg'):
            image_path = os.path.join(directory, filename)
            output_path = os.path.join(output_directory, f"cropped_{filename}")
            
            try:
                with Image.open(image_path) as img:
                    # 裁剪图像
                    cropped_img = img.crop((left, top, right, bottom))
                    cropped_img.save(output_path)
                    print(f"图像 {filename} 已裁剪并保存至: {output_path}")
            except Exception as e:
                print(f"处理图像 {filename} 时出错: {e}")

if __name__ == "__main__":
    # 示例用法
    input_dir = "NJ知识产权"  # 输入目录
    output_dir = "NJ知识产权/cropped"  # 输出目录
    crop_box = (10, 10, 1070, 1440)  # 裁剪框 (left, top, right, bottom)
    crop_images_in_directory(input_dir, output_dir, *crop_box)